package com.study.service.impl;

import com.study.Utils.FileWriterUtils;
import com.study.dao.ArticleRepository;
import com.study.pojo.entity.ArticleDTO;
import com.study.pojo.req.ArticleVo;
import com.study.pojo.resp.BaserResp;
import com.study.service.ArticleService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;

@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    ArticleRepository articleRepository;

    @Autowired
    TemplateEngine templateEngine;



    @Override
    public BaserResp createArticle(ArticleVo articleVo) {
        //1.进行存储，生成静态化模板更新数据库的url
        ArticleDTO articleDTO = new ArticleDTO();
        BeanUtils.copyProperties(articleVo,articleDTO);
         articleRepository.saveAndFlush(articleDTO);
        //2.读取静态化模板生成静态化页面
        Context context = new Context();
        context.setVariable("article",articleDTO);

        String articleDetail = templateEngine.process("articleDetail", context);

        String name = UUID.randomUUID().toString();
        //将静态化页面放置在nginx下
        String s = FileWriterUtils.writerHtml(articleDetail, name);

        //3.修改数据库的静态化页面路径
        articleDTO.setArticleUrl("http://localhost:7000/static/"+name+".html");
        //修改
        articleRepository.saveAndFlush(articleDTO);
        return new BaserResp(1,"新增成！",null,null);
    }

    @Override
    public BaserResp findAll() {

        List<Map<String, Object>> ariticle = articleRepository.findAriticle();
        return new BaserResp(1,"查询成功！",ariticle,null);
    }

    /**
     * 通过id查询
     * @param id
     * @return
     */
    @Override
    public BaserResp findArticleById(Integer id) {
        Optional<ArticleDTO> byId = articleRepository.findById(id);
        if(byId!=null){
            return new BaserResp(1,"查询成功",byId,null);
        }
        return new BaserResp().ERROR();
    }
}
